package com.qq.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qq.bean.Comment;
import com.qq.bean.Dynamics;
import com.qq.dao.BaseDao;
import com.qq.dao.CommentDao;

public class CommentDaoImpl implements CommentDao {
    @Override
    public int insertComment(Comment comment) {
        Connection con = null;
        PreparedStatement ps = null;
        int result = 0;
        String sql = "INSERT INTO comment(user_id,dynamics_id, comment_text, send_date) VALUES (?,?,?,NOW())";

        try {
            con = BaseDao.getCon();
            ps = con.prepareStatement(sql);
            ps.setInt(1, comment.getUser_id());
            ps.setInt(2, comment.getDynamics_id());
            ps.setString(3, comment.getComment_text());
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(con, ps, null);
        }

        return result;
    }

	@Override
	public Map<String,Object> selectAllcomment(int dynamics_id) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		List<String> comments = new ArrayList<String>();
		Map<String,Object> cm = new HashMap<>();
		String sql = "SELECT u.nickName,c.comment_text FROM `comment` c JOIN `users` u ON u.userId = c.user_id WHERE dynamics_id = ? ORDER BY send_date DESC";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, dynamics_id);
			res = ps.executeQuery();
			while(res.next()) {
				String nickName = res.getString("nickName");
				String comment_text = res.getString("comment_text");
				comments.add(comment_text);
				cm.put("nickName",nickName);
				cm.put("comments",comments);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}

		System.out.println(sql);
		return cm;
	}
}